package com.rchat.pocmini.activity.main;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.aso.common.utils.DeviceUtils;
import com.aso.common.utils.ToastUtils;
import com.itsdf07.alog.ALog;
import com.poc.common.utils.BatteryUtils;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.PushMessageOffLineActivity;
import com.rchat.pocmini.bean.JPushBean;
import com.rchat.pocmini.bean2eventbus.EventBusRemoteBean;
import com.rchat.pocmini.common.update.AppUpdateGlobal;
import com.rchat.pocmini.common.update.AppUpdateManager;
import com.rchat.pocmini.global.BundleKeyGlobal;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.service.RchatClientService;
import com.rchat.pocmini.session.PocAirtalkeeSessionManager;
import com.rchat.pocmini.util.SPUtil;
import com.rchat.pocmini.util.Sound;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by itsdf07 on 2017/7/25.
 */

public class MainPresenterImpl extends MainContract.Presenter {
    //JPush handler code
    private static final int JPUSH_INIT = 1;
    private static final int JPUSH_MESSAGE = 2;
    //Jpush init callback err code
    private static final int JPUSH_INIT_ERR = 6002;

    private PocAirtalkeeSessionManager mPocAirtalkeeSessionManager;

    private final Handler mJPushResultHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //Jpush 初始化处理
                case JPUSH_INIT:
                    JPushInterface.setAlias(mActivity, PocAccount.getUserId(), mAliasCallback);
                default:
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
//                    SharedPreferences setting = getSharedPreferences("rchat", MODE_PRIVATE);
//                    setting.edit().putBoolean("Jpush_first_init", false).apply();
                    break;
                case JPUSH_INIT_ERR:
                    // 延迟 60 秒来调用 Handler 设置别名
                    mJPushResultHandler.sendMessageDelayed(mJPushResultHandler.obtainMessage(JPUSH_INIT, alias), 1000 * 60);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    void initJPush() {
        if (PocAccount.getUserId() != null) {//
            // Jpush调用 Handler 来异步设置别名
            Message msg = mJPushResultHandler.obtainMessage(JPUSH_INIT, PocAccount.getUserId());
            mJPushResultHandler.sendMessage(msg);
        }
    }

    @Override
    void queryJPushMessage() {
        mModel.queryJPushMessage(PocAccount.getUserId(), new HttpCallbackImpl<JPushBean>() {
            @Override
            public void onStart() {
                mView.showLoading();
            }

            @Override
            public void onSuccess(JPushBean bean) {
                if (mView == null) {
                    return;
                }
                ALog.d("desc = %s", bean.getDesc());
                gotoShowJPushMessage(bean);
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                if (mView == null) {
                    return;
                }
                ALog.d("code = %s,message = %s", bean, bean.getDesc());
            }

            @Override
            public void onFinish() {
                if (null == mView) {
                    return;
                }
                mView.dismissLoading();
            }
        });
    }

    @Override
    public void pttTaklRequest() {
        if (mPocAirtalkeeSessionManager.getLockedAirSession() == null || mPocAirtalkeeSessionManager.getLockedAirSession().equals("")) {
            mView.showShortToast(R.string.tip_please_lock_a_session);
            Sound.playSound(Sound.PLAYER_CALL_ERROR, mActivity);
            return;
        }
        if (PocService.isPhoneCalling) {
            ToastUtils.showToast("当前PTT不可用");
            return;
        }
        mPocAirtalkeeSessionManager.talkRequest(mPocAirtalkeeSessionManager.getLockedAirSession());
    }

    @Override
    public void pttTalkRelease() {
        mPocAirtalkeeSessionManager.talkRelease(mPocAirtalkeeSessionManager.getLockedAirSession());
    }

    /**
     * 跳转至拉取展示JPush推送失败的消息界面
     *
     * @param bean
     */
    private void gotoShowJPushMessage(JPushBean bean) {
        if (bean.getData().getApplyGroups().size() > 0
                || bean.getData().getApplyFriend().size() > 0
                || bean.getData().getReplyGroup().size() > 0
                || bean.getData().getReplyFriend().size() > 0
                || bean.getData().getExitGroupPush().size() > 0
                || bean.getData().getInviteMembers().size() > 0) {
            Intent intent = new Intent();
            intent.setClass(mActivity, PushMessageOffLineActivity.class);
            intent.putExtra(PushMessageOffLineActivity.KEY_BUNDLE_JPUSHMESSAGE_OBJ, bean.getData());
            mActivity.startActivity(intent);
        }
    }

    @Override
    public void onPStart() {
        if (!BatteryUtils.isIgnoringBatteryOptimizations(mActivity)) {
            BatteryUtils.addWhiteList(mActivity, BatteryUtils.BATTERY_OPTIMIZATION_MODEL_SYSTEM);
        }

        mPocAirtalkeeSessionManager = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance();

        DeviceUtils.getDeviceUtils().setActivityContext(mActivity);
        DeviceUtils.getDeviceUtils().init();

        boolean bindRemoteState = (boolean) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_BIND_REMOTESERVICE, false);
        EventBusRemoteBean bean = new EventBusRemoteBean();
        bean.setCurrentEvent(bindRemoteState ? EventBusRemoteBean.EVENT_STARTREMOTE : EventBusRemoteBean.EVENT_UNBINDREMOTE);
        bean.setTarget(this.getClass(), RchatClientService.class, "onEventBusDispatchRemote");
        EventBus.getDefault().post(bean);

        boolean isStart4Third = mActivity.getIntent().getBooleanExtra(BundleKeyGlobal.INTENT_START_APP_THIRD, false);
        if (isStart4Third) {
            mActivity.moveTaskToBack(true);
        }

        checkAppUpdate();

    }

    private void checkAppUpdate() {
        int vipStatus = (int) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, 0);
        if (vipStatus == 2) {
            checkAppUpdateCallback();
        } else {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    checkAppUpdateCallback();
                }
            }, 3000);
        }
    }

    private void checkAppUpdateCallback() {
        AppUpdateManager.getInstance(mActivity).setDownLoadCallback(new AppUpdateManager.IDownLoadCallback() {
            @Override
            public void onProgress(long progress) {

            }

            @Override
            public void onDownLoadFinish(File file) {
                AppUpdateManager.getInstance(mActivity).openApk(mActivity, file);
            }
        });
        AppUpdateManager.getInstance(mActivity).checkUpdate(AppUpdateGlobal.CheckUpdateModel.AUTO);
    }

}
